package com.lyf.network.practice.nio.chartroom;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author LYF
 * @date 2022/6/24
 */
public class NioServer {
    static void start() throws IOException, InterruptedException {
        // 1.打开Channel -- 联系TCP的创建方式--
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        // 2.绑定端口号
        //socketChannel.socket().bind(new InetSocketAddress(8899));
        socketChannel.bind(new InetSocketAddress(8899));
        System.out.println("服务启动成功!");
        // 3.设置非阻塞
        socketChannel.configureBlocking(false);
        // 4.创建选择器
        Selector selector = Selector.open();
        // 5.将通道注册到选择器上面进行监听--通道
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 6.循环连接
        for(;;){
            int selection = selector.select();
            if(selection==0){
                // 未有监听到连接
                TimeUnit.SECONDS.sleep(1);
                System.out.println("waiting 1 s to connect...");
                continue;
            }

            Set<SelectionKey> keySet = selector.selectedKeys();

            for(SelectionKey key:keySet){
                 if(key.isAcceptable()){
                     System.out.println("listening accept");
                     acceptOpt(socketChannel,selector);
                 }else if(key.isWritable()){
                     System.out.println("listening writeable");
                    // writeOpt()
                 }
            }
        }

    }

    /**接入*/
    private static void acceptOpt(ServerSocketChannel socketChannel,Selector selector) throws IOException {
        SocketChannel socketChannel1 = socketChannel.accept();

        socketChannel1.configureBlocking(false);

        socketChannel1.register(selector, SelectionKey.OP_READ);

        socketChannel1.write(Charset.forName("UTF-8").encode("hello"));
    }






    public static void main(String[] args) throws IOException, InterruptedException {
          start();
    }
}
